package com.gemantic.task.service.impl;

import java.util.List;
import javax.annotation.Resource;

import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Service;

import com.gemantic.task.config.scheduler.JobStartCondition;
import com.gemantic.task.model.XxlJobGroup;
import com.gemantic.task.model.XxlJobInfo;
import com.gemantic.task.service.XxlTaskService;
import com.gemantic.task.service.support.XxlTaskFeignClient;
import com.xxl.job.core.biz.model.ReturnT;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@Service
//@Conditional(JobStartCondition.class)
@Slf4j
public class XxlTaskServiceImpl implements XxlTaskService {

    @Resource
    private XxlTaskFeignClient xxlTaskFeignClient;


    @Override
    public String add(XxlJobInfo jobInfo) {
        String appname = jobInfo.getAppname();
        if (StrUtil.isEmpty(appname)) {
            throw new IllegalArgumentException("appname必填参数");
        }
        ReturnT<XxlJobGroup> jobGroupByAppName = xxlTaskFeignClient.findJobGroupByAppName(appname);
        if (!(ReturnT.SUCCESS_CODE == jobGroupByAppName.getCode())) {

            String errorName = StrUtil.format("根据appName:{}获取执行器为Null", appname);
            throw new IllegalArgumentException(errorName);
        }
        XxlJobGroup content = jobGroupByAppName.getContent();
        int groupId = content.getId();
        jobInfo.setJobGroup(groupId);
        ReturnT<String> addResult = xxlTaskFeignClient.add(jobInfo);

        if (ReturnT.SUCCESS_CODE == addResult.getCode()) {
            return addResult.getContent();
        }
        log.error("add jobInfo error log:{}", JSONUtil.toJsonStr(addResult));
        return null;
    }

    @Override
    public String update(XxlJobInfo jobInfo) {
        ReturnT<String> update = xxlTaskFeignClient.update(jobInfo);
        return update.getContent();
    }

    @Override
    public String start(int id) {
        return xxlTaskFeignClient.start(id).getContent();
    }

    @Override
    public String stop(int id) {
        return xxlTaskFeignClient.stop(id).getContent();
    }

    @Override
    public XxlJobInfo loadById(int id) {
        return xxlTaskFeignClient.getJob(id).getContent();
    }

    @Override
    public List<String> nextTriggerTime(String scheduleType, String scheduleConf) {
        return xxlTaskFeignClient.nextTriggerTime(scheduleType, scheduleConf).getContent();
    }

    @Override
    public XxlJobGroup findJobGroupByAppName(String appName) {
        return xxlTaskFeignClient.findJobGroupByAppName(appName).getContent();
    }


}
